<template>
  <div class="login">
    <div class="loginBox">
      <h2 class="title">小学算术教学系统</h2>
      <div class="tab">
        <div class="tab-item" :class="activeIndex == 1 ? 'active' : ''" @click="handleSelect(1)">学生</div>
        <div class="tab-item" :class="activeIndex == 2 ? 'active' : ''" @click="handleSelect(2)">教师</div>
        <div class="tab-item" :class="activeIndex == 3 ? 'active' : ''" @click="handleSelect(3)">管理员</div>
      </div>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        active-text-color="#fff"
      >
        <el-form-item label="账号" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input type="passWord" v-model="ruleForm.passWord" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input class="code-input" v-model="ruleForm.code" autocomplete="off"></el-input>
          <div
            class="codeImg"
            @click="getcode()"
            style="width: 100px; height: 40px; background: white; float: right"
          >
            <img class="autoCode" :src="codeImg" alt="验证码" />
          </div>
        </el-form-item>
        <el-form-item v-if="activeIndex == '1'">
          <el-button type="primary" @click="submitForm1('ruleForm')">登录</el-button>
        </el-form-item>
        <el-form-item v-if="activeIndex == '2'">
          <el-button type="primary" @click="submitForm2('ruleForm')">登录</el-button>
        </el-form-item>
        <el-form-item v-if="activeIndex == '3'">
          <el-button type="primary" @click="submitForm3('ruleForm')">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from "../request/axios";
import loginRequest from "../request/login";
import cookie from "js-cookie";
export default {
  data() {
    // 登录验证规则
    var userName = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("账号不能为空"));
      } else {
        return callback();
      }
    };
    var passWord = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("密码不能为空"));
      } else {
        return callback();
      }
    };
    var code = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        if (/^[a-z0-9]{5,12}$/.test(value)) {
          callback();
        } else {
          callback(new Error("验证码有误"));
        }
      }
    };
    return {
      account: "",
      codeImg: "", // 验证码图片
      activeIndex: "1", //tab切换下标
      ruleForm: {
        userName: "",
        passWord: "",
        code: ""
      },
      rules: {
        userName: [{ validator: userName, trigger: "blur" }],
        passWord: [{ validator: passWord, trigger: "blur" }],
        code: [{ validator: code, trigger: "blur" }]
      }
    };
  },

  methods: {
    // tab切换开关
    handleSelect(index) {
      this.activeIndex = index;
    },
    // 用户登录
    submitForm1(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          loginRequest
            .studentLogin({
              account: this.ruleForm.userName,
              passWord: this.ruleForm.passWord,
              txt: this.ruleForm.code
            })
            .then(res => {
              console.log(res);
              if (res.data.success == true) {
                let userinfo = res.data.result;
                userinfo.type = "student"
                // 获取token  存储在本地
                cookie.set("satoken", userinfo.satoken);
                // 获取用户信息  存储在本地
                window.localStorage.setItem(
                  "userinfo",
                  JSON.stringify(userinfo)
                );
                this.$notify({
                  title: "欢迎回来",
                  type: "success"
                });
                this.$router.push({ path: "/" });
              } else {
                this.$message.error(res.data.message);
              }
            });
        } else {
          this.$message.error("请检查您的账号密码!");
          return false;
        }
      });
    },
    // 教师登录
    submitForm2(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          loginRequest
            .teacherLogin({
              account: this.ruleForm.userName,
              passWord: this.ruleForm.passWord,
              txt: this.ruleForm.code
            })
            .then(res => {
              console.log(res);
              if (res.data.success == true) {
                let userinfo = res.data.result;
                userinfo.type = "teacher"
                // 获取token  存储在本地
                cookie.set("satoken", userinfo.satoken);
                // 获取用户信息  存储在本地
                window.localStorage.setItem(
                  "userinfo",
                  JSON.stringify(userinfo)
                );
                this.$notify({
                  title: "欢迎回来",
                  type: "success"
                });
                this.$router.push({ path: "/" });
              } else {
                this.$message.error(res.data.message);
              }
            });
        } else {
          this.$message.error("请检查您的账号密码!");
          return false;
        }
      });
    },
    // 管理员
    submitForm3(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          loginRequest
            .adminLogin({
              userName: this.ruleForm.userName,
              passWord: this.ruleForm.passWord,
              txt: this.ruleForm.code
            })
            .then(res => {
              console.log(res);
              if (res.data.success == true) {
                let userinfo = res.data.result;
                userinfo.type = "admin"
                // 获取token  存储在本地
                cookie.set("satoken", userinfo.satoken);
                // 获取用户信息  存储在本地
                window.localStorage.setItem(
                  "userinfo",
                  JSON.stringify(userinfo)
                );
                this.$notify({
                  title: "欢迎回来",
                  type: "success"
                });
                this.$router.push({ path: "/adminHome" });
              } else {
                this.$message.error(res.data.message);
              }
            });
        } else {
          this.$message.error("请检查您的账号密码!");
          return false;
        }
      });
    },

    //点击获取验证码
    getcode() {
     this.codeImg =
        axios.defaults.baseURL +
        "file/getImg" +
        "?data = " +
        new Date().getTime();
    }
  },

  //生命周期（页面加载时执行）
  created() {
    // 页面加载时生成验证码
    this.codeImg =
      axios.defaults.baseURL +
      "file/getImg" +
      "?data = " +
      new Date().getTime();
  }
};
</script>

<style lang="scss" scoped>
@import "../css/myLogin.scss";
.autoCode {
  width: 100%;
  height: 100%;
}
</style>